var gmarket = {
	/**
	 * 获取所有市场
	 */
	get: function(callback, isOrder) {
		var __self = this;
		ghttp.get('/market', null, function(resp) {
			if(!resp.success) {
				callback();
				return;
			}

			var localKey = 'local-location';
			var markets = resp.result;
			var expire = 3600000; // 1 hour

			markets.forEach(function(item) {
				item.marketName = item.marketName.replace('上海市普陀区', '');
			});


			if(isOrder === false) {
				callback(markets);
			} else {
				var location = localStorage.getItem(localKey);
				if(location) {
					location = JSON.parse(location);
					if(location.time*1 - Date.now() > expire) {
						localStorage.removeItem(localKey);
						location = null;
					}
				}

				if(location) {
					// sort
					__self.__orderByDistance(location.lng, location.lat, markets, callback);
				} else {
					// get current locaton
					var geolocation = new BMap.Geolocation();
					geolocation.getCurrentPosition(function(r) {
						if (this.getStatus() == BMAP_STATUS_SUCCESS) {
							var lng = r.point.lng;
							var lat = r.point.lat;
							// set local
							localStorage.setItem(localKey, JSON.stringify({ lng: lng, lat: lat, time: Date.now() }));
							// sort
							__self.__orderByDistance(lng, lat, markets, callback);
						} else {
							callback(markets);
						}
					}, {enableHighAccuracy: true});
				}
			}
		});
	},

	/**
	 * 距离排序
     */
	__orderByDistance: function(lng, lat, markets, callback) {
		var __self = this;
		var point1 = new BMap.Point(lng,lat);
		// 计算两点间距离
		var map = new BMap.Map("map-container");
		markets.forEach(function(m) {
			var point2 = new BMap.Point(m.longitude,m.latitude);
			var distance = map.getDistance(point1,point2);
			m.distanceV = distance*1;
			m.distance = __self.__format(distance*1);
		});

		// 按照距离排序
		markets = markets.sort(function(m, n) {
			return m.distanceV - n.distanceV;
		});

		callback(markets);
	},

	/**
	 * 距离格式
     */
	__format: function(distance) {
		if(distance > 1000) {
			var d = distance / 1000;
			d = d.toFixed(1);
			return d + 'km';
		} else {
			return distance.toFixed(0) + 'm';
		}
	}
};